<?php

namespace Common\Service;

// +----------------------------------------------------------------------
// | 文件 TokenService.class.php
// +----------------------------------------------------------------------
// | 说明 授权TOKEN
// +----------------------------------------------------------------------
// | 
// +----------------------------------------------------------------------
// | Author: 谢赤心 Legend. <xcx_legender@qq.com>
// +----------------------------------------------------------------------

Class TokenService extends BaseService
{

     protected $_validate = array(
        array('app_token', 'require', '授权码不能为空', self::MUST_VALIDATE , 'regex', self::MODEL_BOTH),
        array('app_token', '', '授权码存在', self::MUST_VALIDATE , 'unique', self::MODEL_BOTH),
    );

    /* 用户模型自动完成 */
    protected $_auto = array(
        array('app_token', 'htmlspecialchars', self::MODEL_BOTH, 'function'),
        array('mobile_imie', 'htmlspecialchars', self::MODEL_BOTH, 'function'),
        array('uid', 'intval', self::MODEL_BOTH, 'function'),
        array('last_time', NOW_TIME, self::MODEL_BOTH),
        array('status', 1, self::MODEL_INSERT),
    );

    /**
    *新增token记录数据
    */
    public function addToken($uid, $imie, &$appToken, $platform = 0){
        $curTime = time();
        $str = $uid.$imie.$curTime;
        $appToken = md5($str);
        $map = ['uid' => $uid, 'platform' => $platform];
        if($data = $this->where($map)->find()){
            unset($data['_id']);
            $data['app_token'] = $appToken;
            $data['mobile_imie'] = $imie;
            $data['status'] = 1;
            $type = 0;
        }else{
            $data = array('uid'=>$uid, 'app_token'=>$appToken, 'mobile_imie'=>$imie, 'status'=>1);
            $data['platform'] = $platform;
            $type = 1;
        }
        
        return $this->doAct($data, $type);
    }

    /**
    *新增或更新数据
    */
    private function doAct($data, $type=1){
        $data = $this->create($data);
        if(!$data)
            return false;
        if($type == 1)
            $res = $this->add($data);
        else
        {
            $res = $this->save($data);
        }
        return $res?true:false;
    }

    /**
    *用户注销
    */
    public function logout($token){
        $map = array('app_token'=>$token,);
        $info = $this->where($map)->find();
        if(empty($info)){
            return -1;
        }elseif($info['status'] != 1){
            return -2;
        }else{
            $info['status'] = 0;
            $data = $this->create($info);
            if($this->save($data))
                return 1;
            else
                return -3;
        }
    }

}